﻿using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace DynamicQuartz.Common
{
    public class DingDingNotification
    {
        public static void Notification(string msg)
        {
            var robot = new DingTalkRobot();
            robot.SendTextMessageAsync(msg).GetAwaiter().GetResult();
        }
    }

    public class DingTalkRobot
    {
        private readonly string _webhookUrl;

        public DingTalkRobot()
        {
            _webhookUrl = string.Format("https://oapi.dingtalk.com/robot/send?access_token={0}","token");
        }

        public async Task SendTextMessageAsync(string message)
        {
            var payload = new
            {
                msgtype = "text",
                text = new
                {
                    content = message
                }
            };

            await SendMessageAsync(payload);
        }

        private async Task SendMessageAsync(object payload)
        {
            using (var client = new HttpClient())
            {
                var json = JsonConvert.SerializeObject(payload);
                var content = new StringContent(json, Encoding.UTF8, "application/json");

                var response = await client.PostAsync(_webhookUrl, content);
                response.EnsureSuccessStatusCode();

                var responseBody = await response.Content.ReadAsStringAsync();
                Console.WriteLine($"Response: {responseBody}");
            }
        }
    }

}
